<template>
  <view class="uni-numbox">
    <view
      v-if="showStep"
      @click="_calcValue('minus')" class="uni-numbox__minus uni-numbox-btns" :style="{background}">
      <text class="uni-numbox--text" :class="{ 'uni-numbox--disabled': inputValue <= min || disabled }"
            :style="{color}">-
      </text>
    </view>
    <view class="uni-easyinput__content">
      <input :disabled="disabled"
             @focus="onFocus"
             @blur="onBlur"
             class="uni-numbox__value"
             type="digit"
             v-model="inputValue"
             @input="onInput"
             :style="{background, color}"
             :placeholder="placeholder"
             placeholder-class="placeholder-class uni-easyinput__placeholder-class"
      />
    </view>
    <view
      v-if="showStep"
      @click="_calcValue('plus')" class="uni-numbox__plus uni-numbox-btns" :style="{background}">
      <text class="uni-numbox--text" :class="{ 'uni-numbox--disabled': inputValue >= max || disabled }"
            :style="{color}">+
      </text>
    </view>
  </view>
</template>
<script>/**
 * NumberBox 数字输入框
 * @description 带加减按钮的数字输入框
 * @tutorial https://ext.dcloud.net.cn/plugin?id=31
 * @property {Number} value 输入框当前值
 * @property {Number} min 最小值
 * @property {Number} max 最大值
 * @property {Number} step 每次点击改变的间隔大小
 * @property {String} background 背景色
 * @property {String} color 字体颜色（前景色）
 * @property {Boolean} disabled = [true|false] 是否为禁用状态
 * @event {Function} change 输入框值改变时触发的事件，参数为输入框当前的 value
 * @event {Function} focus 输入框聚焦时触发的事件，参数为 event 对象
 * @event {Function} blur 输入框失焦时触发的事件，参数为 event 对象
 */
import { StringUtils } from '../../../../utils/StringUtils'

export default {
  name: 'UniNumberBox',
  emits: ['change', 'input', 'update:modelValue', 'blur', 'focus'],
  props: {
    placeholder: {
      type: String,
      default: ' '
    },
    placeholderStyle: String,
    showStep: {
      type: Boolean,
      default: false
    },
    value: {
      type: [Number, String],
      default: ''
    },
    modelValue: {
      type: [Number, String],
      default: ''
    },
    abs: {
      type: Boolean,
      default: true
    },
    min: {
      type: [Number, String],
      default: ''
    },
    max: {
      type: [Number, String],
      default: ''
    },
    step: {
      type: Number,
      default: 1
    },
    background: {
      type: String,
      default: '#fff'
    },
    color: {
      type: String,
      default: '#333'
    },
    disabled: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      inputValue: ''
    }
  },
  watch: {
    value: {
      immediate: true,
      handler(val) {
        this.inputValue = val === '' ? '' : val
        this.$emit('change', this.inputValue)
        // TODO vue2 兼容
        this.$emit('input', this.inputValue)
        // TODO vue3 兼容
        this.$emit('update:modelValue', this.inputValue)
      }
    },
    modelValue: {
      immediate: true,
      handler(val) {
        this.inputValue = val === '' ? '' : val
        this.$emit('change', this.inputValue)
        // TODO vue2 兼容
        this.$emit('input', this.inputValue)
        // TODO vue3 兼容
        this.$emit('update:modelValue', this.inputValue)
      }
    }
  },
  methods: {
    _calcValue(type) {
      if (this.disabled) {
        return
      }
      const scale = this._getDecimalScale()
      let value = this.inputValue * scale
      let step = this.step * scale
      if (type === 'minus') {
        value -= step
        if (value < (this.min * scale)) {
          return
        }
        if (value > (this.max * scale)) {
          value = this.max * scale
        }
      }

      if (type === 'plus') {
        value += step
        if (value > (this.max * scale)) {
          return
        }
        if (value < (this.min * scale)) {
          value = this.min * scale
        }
      }

      this.inputValue = (value / scale).toFixed(String(scale).length - 1)
      this.$emit('change', +this.inputValue)
      // TODO vue2 兼容
      this.$emit('input', +this.inputValue)
      // TODO vue3 兼容
      this.$emit('update:modelValue', +this.inputValue)
    },
    _getDecimalScale() {
      let scale = 1
      // 浮点型
      if (~~this.step !== this.step) {
        scale = Math.pow(10, String(this.step).split('.')[1].length)
      }
      return scale
    },
    onInput() {

      const { min, abs } = this
      let value = this.inputValue.replace(/[^-0-9.]/g, '')
      if(StringUtils.isEmptyOrNull(value)){
        this.$emit('update:modelValue', value)
        this.$emit('input', value)
        this.inputValue = ''
        return
      }
      let vF = parseFloat(value)
      if (!StringUtils.isEmptyOrNull(min)) {
        if (abs) {
          value = Math.abs(vF)
        } else {
          value = Math.max(min, vF)
        }
      }

      this.$nextTick(() => {
        this.$emit('update:modelValue', value)
        this.$emit('input', value)
        this.inputValue = value
      })
    },
    onBlur(event) {
      this.$emit('blur', event)
      let value = event.detail.value
      if (StringUtils.isEmptyOrNull(value)) {
        // this.inputValue = 0;
        return
      }
      value = (value).replace(/[^-0-9.]/ig, '')
      value = +value
      this.$nextTick(() => {
        this.inputValue = value
        this.$emit('change', +this.inputValue)
        this.$emit('input', +this.inputValue)
      })
    },
    onFocus(event) {
      this.$emit('focus', event)
    }
  }
}
</script>
<style lang="scss" scoped>
$box-height: 35px;
$bg: #fff;
$br: 2px;
$color: #333;
$uni-border-1: #DCDFE6 !default;
.uni-numbox {
  /* #ifndef APP-NVUE */
  display: flex;
  /* #endif */
  /* #ifndef APP-NVUE */
  width: 100%;
  /* #endif */
  flex: 1;
  position: relative;
  text-align: left;
  color: #333;
  font-size: 14px;
}

//
.uni-numbox-btns {
  /* #ifndef APP-NVUE */
  display: flex;
  /* #endif */
  flex-direction: row;
  align-items: center;
  justify-content: center;
  padding: 0 16px;
  background-color: $bg;
  /* #ifdef H5 */
  cursor: pointer;
  /* #endif */
}

.uni-easyinput__content {
  /* #ifndef APP-NVUE */
  width: 100%;
  display: flex;
  box-sizing: border-box;
  // min-height: 36px;
  /* #endif */
  flex-direction: row;
  align-items: center;
  // 处理border动画刚开始显示黑色的问题
  border-color: #fff;
  transition-property: border-color;
  transition-duration: 0.3s;
}

//
.uni-numbox__value {
  padding-left: 10px;
  /* #ifndef APP-NVUE */
  width: auto;
  /* #endif */
  position: relative;
  overflow: hidden;
  font-size: 14px;
}

.uni-numbox__minus {
  border-top-left-radius: $br;
  border-bottom-left-radius: $br;
  border-right: 1px solid $uni-border-1;
}

.uni-numbox__plus {
  border-top-right-radius: $br;
  border-bottom-right-radius: $br;
  border-left: 1px solid $uni-border-1;
}

.uni-numbox--text {
  // fix nvue
  line-height: 20px;
  font-weight: 300;
  color: $color;
}

//
.uni-numbox .uni-numbox--disabled {
  color: #cccccc !important;
  /* #ifdef H5 */
  cursor: not-allowed;
  /* #endif */
}


.uni-easyinput__placeholder-class {
  // color: #f5f7fa !important;
  font-size: 14px;
}

</style>
